package com.cloudbroker.bcs.platform.dav.middle.bizservice.impl;

import java.math.BigDecimal;
import java.util.Date;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.cloudbroker.bcs.common.util.StringUtil;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.common.util.ValueUtil;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.QuestionErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.SysMgtErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.status.AnswerStatus;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.status.PaySource;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.status.PayStatus;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.gold.result.GoldChangeResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.gold.vo.GoldTransForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.reward.RewardBizService;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.reward.vo.RewardInfoForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.reward.vo.RewardNumVo;
import com.cloudbroker.bcs.platform.dav.middle.context.HSBCPSBizDataContext;
import com.cloudbroker.bcs.platform.dav.middle.entity.Broker;
import com.cloudbroker.bcs.platform.dav.middle.entity.Customer;
import com.cloudbroker.bcs.platform.dav.middle.entity.CustomerBrokerRel;
import com.cloudbroker.bcs.platform.dav.middle.entity.PayWater;
import com.cloudbroker.bcs.platform.dav.middle.entity.Question;
import com.cloudbroker.bcs.platform.dav.middle.entity.ViewpointMsg;
import com.cloudbroker.bcs.platform.dav.middle.extservice.gold.GoldService;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerManagerService;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerService;
import com.cloudbroker.bcs.platform.dav.middle.service.CustomerBrokerRelService;
import com.cloudbroker.bcs.platform.dav.middle.service.CustomerService;
import com.cloudbroker.bcs.platform.dav.middle.service.PayWaterService;
import com.cloudbroker.bcs.platform.dav.middle.service.QuestionService;
import com.cloudbroker.bcs.platform.dav.middle.service.ViewpointMsgService;
import com.cloudbroker.bcs.platform.dav.middle.util.GoldTokenUtil;
import com.cloudbroker.bcs.platform.dav.middle.util.PositionStrUtil;
import com.hundsun.jres.common.util.UUID;

/**
 * Created by zhaojp18008 on 2016/5/9.
 */
@Service
public class RewardBizServiceImpl implements RewardBizService {
    @Resource
    private ViewpointMsgService viewpointMsgService;
    
    @Resource
    private PayWaterService payWaterService;
    
    @Resource
    private CustomerService customerService;
    
    @Resource
    private BrokerService brokerService;
    
    @Resource
    private CustomerBrokerRelService customerBrokerRelService;
    
    @Resource
    private QuestionService questionService;
    
    @Resource
    private GoldService goldService;
    
    @Resource
    private BrokerManagerService brokerManagerService;
    
    private static final Logger logger = LoggerFactory.getLogger(RewardBizServiceImpl.class);
    
    @Override
    public RewardNumVo funcClickReward(RewardInfoForm param) {
        RewardNumVo rewardNumVo = new RewardNumVo();
        Customer customer = HSBCPSBizDataContext.getCustomer();
        Integer tenant_id = customer.getTenant_id();
        String pay_amount = param.getPay_amount();
        BigDecimal amount = new BigDecimal(pay_amount);
        String target_id = param.getTarget_id();
        String pay_source = param.getPay_source();
        String orderId = UUID.randomUUID().toString();
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        Broker b = brokerService.getById(broker_id, tenant_id);
        ViewpointMsg msg = null;
        Question ques = null;
        if (!StringUtil.isEmpty(target_id)) {
            //target_id不为空，若pay_source为实时评打赏，返回错误
            if (String.valueOf(PaySource.COMMENT.getVal()).equals(pay_source)) {
                return VOUtil.genErrorResult(SysMgtErr.PAY_SOURCE_EXCEPTION, RewardNumVo.class);
            }
            //付费观点
            if (String.valueOf(PaySource.VIEWPOINT_READ.getVal()).equals(pay_source)) {
                msg = this.viewpointMsgService.getSendViewpointByID(target_id);
                if (null == msg) {
                    return VOUtil
                            .genErrorResult(HSBCPSErrorCodes.SysMgtErr.NO_SUCH_VIEWPOINT_ID, RewardNumVo.class);
                }
                if (msg.getPrice() == null || msg.getPrice().compareTo(BigDecimal.ZERO) < 1) {
                    return VOUtil.genErrorResult(HSBCPSErrorCodes.SysMgtErr.VIEWPOINT_FREE, RewardNumVo.class);
                }
                if (msg.getPrice().compareTo(amount) != 0) {
                    return VOUtil.genErrorResult(HSBCPSErrorCodes.SysMgtErr.PAY_PRICE_ERR, RewardNumVo.class);
                }
                PayWater pw = this.payWaterService.getViewpointPayWater(Long.valueOf(target_id),
                        PaySource.VIEWPOINT_READ.getVal(), customer.getCustomer_id());
                if (null != pw) {
                    return VOUtil.genErrorResult(HSBCPSErrorCodes.SysMgtErr.PAY_PRICE_EXIST, RewardNumVo.class);
                }
                msg.setReward_num(ValueUtil.getInt(msg.getReward_num(), 0) + 1);
                msg.setTotal_income(msg.getTotal_income().add(amount));
            }
            //问与答打赏
            if (String.valueOf(PaySource.QUESTION.getVal()).equals(pay_source)) {
                ques = this.questionService.get(target_id);
                if (null != ques) {
                    if (!broker_id.equals(ques.getBroker_id())) {
                        return VOUtil.genErrorResult(SysMgtErr.NO_SUCH_QUESTION, RewardNumVo.class);
                    }
                    if (null == ques.getAnswer_status()
                            || AnswerStatus.ANSWERD.getVal() != Integer.parseInt(ques.getAnswer_status())) {
                        return VOUtil.genErrorResult(QuestionErr.NO_ANSWER, RewardNumVo.class);
                    }
                } else {
                    return VOUtil.genErrorResult(SysMgtErr.NO_SUCH_QUESTION, RewardNumVo.class);
                }
                ques.setReward_num(ValueUtil.getInt(ques.getReward_num(), 0) + 1);
                rewardNumVo.setReward_num(ques.getReward_num());
                ques.setTotal_income(ValueUtil.getBigDecimal(ques.getTotal_income(), new BigDecimal(0)).add(amount));
                
            }
            
            //付费调研
            if (String.valueOf(PaySource.SURVEY.getVal()).equals(pay_source)) {
                logger.info("pay for survey, stockcode:" + target_id + ", customer:" + customer + ",broker:" + b);
            }
        } else {
            //target_id为空，表示实时评打赏，若pay_source不为实时评打赏，返回错误
            if (!String.valueOf(PaySource.COMMENT.getVal()).equals(pay_source)) {
                return VOUtil.genErrorResult(SysMgtErr.PAY_SOURCE_EXCEPTION, RewardNumVo.class);
            }
        }
        
        //调金币系统转账
        GoldTransForm form = new GoldTransForm();
        form.setUser_token(GoldTokenUtil.getGoldToken());
        form.setUser_id(customer.getCustomer_key());
        form.setTenant_id(String.valueOf(tenant_id));
        form.setTarget_user_id(b.getBroker_key());
        form.setExtrans_id(orderId);
        form.setOccur_amount(pay_amount);
        form.setRemark(PaySource.getDescription(Integer.parseInt(pay_source)));
        GoldChangeResult backVo = goldService.goldTrans(form);
        if (!VOUtil.isSuccess(backVo)) {
            /*由于两个系统错误码定义不一样，这里使用错误提示进行判断*/
            if (backVo.getError_info().contains("余额不足")) {
                return VOUtil.genErrorResult(HSBCPSErrorCodes.PayErr.INSUFFICIENT_FUNDS, RewardNumVo.class);
            }
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PayErr.PAY_ERR, RewardNumVo.class);
        }
        
        String uf30transId = backVo.getTrans_id();
        PayWater payWater = new PayWater();
        payWater.setTrans_id(orderId);
        payWater.setUf30_trans_no(uf30transId);
        payWater.setBroker_id(broker_id);
        payWater.setCustomer_id(customer.getCustomer_id());
        payWater.setReal_pay_balance(amount);
        payWater.setPay_status(PayStatus.SUC.getVal());
        payWater.setCreate_time(new Date());
        payWater.setPay_remark(PaySource.getDescription(Integer.parseInt(pay_source)));
        payWater.setPay_source(pay_source);
        if (!StringUtil.isEmpty(target_id)) {
            payWater.setTarget_id(Long.parseLong(target_id));
        }
        payWater.setPosition_str(PositionStrUtil.getPositionStr());
        
        this.payWaterService.save(payWater);
        
        CustomerBrokerRel rel = customerBrokerRelService.getByBrokerIdAndCustomerId(broker_id,
                customer.getCustomer_id());
        if (rel != null) {
            if (rel.getReward_num() == null) {
                rel.setReward_num(1);
                rel.setReward_amount(amount);
            } else {
                rel.setReward_num(rel.getReward_num() + 1);
                rel.setReward_amount(rel.getReward_amount().add(amount));
            }
            customerBrokerRelService.updateCAS(rel);
        }
        
        if (!StringUtil.isEmpty(target_id)) {
            //付费观点
            if (String.valueOf(PaySource.VIEWPOINT_READ.getVal()).equals(pay_source)) {
                this.viewpointMsgService.update(msg);
            }
            //问与答打赏
            if (String.valueOf(PaySource.QUESTION.getVal()).equals(pay_source)) {
                this.questionService.update(ques);
            }
        }
        return VOUtil.setSuccessResult(rewardNumVo);
    }
    
}
